package com.yiwan.app.preventionsis.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.android.volley.http.RequestManager;
import com.app.tianwan.tianwanframe.http.HttpCallBack;
import com.app.tianwan.tianwanframe.ui.ActivityStack;
import com.app.tianwan.tianwanframe.ui.ViewInject;
import com.app.tianwan.tianwanframe.utils.LogUtil;
import com.app.tianwan.tianwanframe.utils.SystemTool;
import com.app.tianwan.tianwanframe.utils.TimeUtils;
import com.yiwan.app.preventionsis.R;
import com.yiwan.app.preventionsis.bean.CheckUpdateData;
import com.yiwan.app.preventionsis.config.GlobalCfg;
import com.yiwan.app.preventionsis.config.ImageResManager;
import com.yiwan.app.preventionsis.net.HttpClient;
import com.yiwan.app.preventionsis.ui.MainActivity;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

public class UpdateManager {

    public static final String SERVER_URL = "http://7xio6o.com2.z0.glb.qiniucdn.com/";
    private static final String CACHE_RESFILE = "res.zip";

    private static UpdateManager instance;
    private HttpClient mHttpClient;
    private Context mContext;
    private boolean isUpdatingRes = false;
    private String mUrl;
    private String mContent;
    private Date mTime;

    public static UpdateManager getInstance(Context context){
        if(instance == null){
            LogUtil.d("new update manager");
            instance = new UpdateManager();
        }
        instance.mContext = context.getApplicationContext();
        instance.mHttpClient = new HttpClient(context);
        return instance;
    }

    public void checkUpdateFromPush(Context brContext){
        ActivityStack activityStack = ActivityStack.getInstance();
        if(activityStack.getCount() == 0 || activityStack.findActivity(MainActivity.class) == null){
            Intent intent = new Intent(brContext, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            brContext.startActivity(intent);
        } else {
            if(SystemTool.isforeHead(brContext, MainActivity.class)) {
                checkVersion();
            } else {
                Intent intent = new Intent(brContext, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                brContext.startActivity(intent);
                checkUpdate();
            }
        }
    }

    /**
     * 版本更新接口
     */
    public void checkUpdate() {
        if(!SystemTool.hasNet(mContext)) return;
        if(!SystemTool.isWiFi(mContext)) return;
        checkVersion();
    }

    /**
     * 检查应用和资源版本
     */
    private void checkVersion(){
        if(GlobalCfg.DEBUG_MODE){
            Toast.makeText(mContext, "checkVersion", Toast.LENGTH_SHORT).show();
        }
        LogUtil.d("is downloading " + isUpdatingRes);
        if(isUpdatingRes){
            showResUpdateDialog(mContent, mUrl, mTime, true);
            return;
        }
        if(dialog != null && dialog.isShowing()){
            LogUtil.d("Dialog is showing");
            return;
        }
        final int resVersionCode;
        try {
            resVersionCode = ImageResManager.getInstance().getResVersion();
            LogUtil.d("resVersionCode: " + resVersionCode);
        } catch (IOException e) {
            LogUtil.d(e);
            Toast.makeText(mContext, "资源加载错误，请重新安装应用", Toast.LENGTH_SHORT).show();
            return;
        }
        final int appVersionCode = SystemTool.getAppVersionCode(mContext);
        mHttpClient.checkUpdate(new RequestManager.RequestListener<CheckUpdateData>() {
            @Override
            public void onRequest() {
            }

            @Override
            public void onSuccess(CheckUpdateData response, String url, Map<String, String> param) {
                int lastVersion, lastResVersion, resSupportMinVersion;
                try {
                    lastVersion = Integer.parseInt(response.getLastVersion());
                } catch (NumberFormatException e) {
                    lastVersion = 0;
                }
                try {
                    lastResVersion = Integer.parseInt(response.getResLastVersion());
                } catch (NumberFormatException e) {
                    lastResVersion = 0;
                }
                try {
                    resSupportMinVersion = Integer.parseInt(response.getResSupportMinVersion());
                } catch (NumberFormatException e) {
                    resSupportMinVersion = 0;
                }
                LogUtil.d("lastResVersion: " + lastResVersion);
                if(GlobalCfg.DEBUG_MODE){
                    Toast.makeText(mContext, "net lastResVersion" + lastResVersion, Toast.LENGTH_SHORT).show();
                }
                if (appVersionCode < lastVersion) {
                    showUpdateDialog(response.getLastVersionDesc(), response.getLastVersionUrl(), response.getLastVersionTime());
                } else if (resVersionCode < lastResVersion) {
                    showResUpdateDialog(response.getResLastVersionDesc(), response.getResLastVersionUrl(), response.getResLastVersionTime(), false);
                } else if (appVersionCode < resSupportMinVersion) {
                    showUpdateDialog(response.getLastVersionDesc(), response.getLastVersionUrl(), response.getLastVersionTime());
                }
            }

            @Override
            public void onError(String errorMsg, int resCode) {
                LogUtil.d("check version error: " + errorMsg);
            }

            @Override
            public void onTimeout() {
                LogUtil.d("check version timeout");
            }
        });
    }

    private AlertDialog dialog;
    private TextView title;
    private TextView stateTxt;
    private ProgressBar progressBar;
    private TextView progressTxt;
    private Button ok;
    private Button cancel;
    private TextView content;
    private RelativeLayout progressFrame;
    private ScrollView descFrame;
    private LinearLayout resLoadingFrame;

    /**
     * 弹出更新提示对话框
     */
    private void showUpdateDialog(String desc, final String url, Date updateTime) {
        Activity activity = ActivityStack.getInstance().topActivity();
        if(activity != null){
            mContent = desc;
            mUrl = url;
            mTime = updateTime;
            View dialogRoot = LayoutInflater.from(mContext).inflate(R.layout.update_dialog, null, false);
            title = (TextView)dialogRoot.findViewById(R.id.update_title);
            ok = (Button)dialogRoot.findViewById(R.id.update_ok);
            cancel = (Button)dialogRoot.findViewById(R.id.update_cancel);
            content = (TextView)dialogRoot.findViewById(R.id.update_content);
            progressFrame = (RelativeLayout)dialogRoot.findViewById(R.id.update_res_progress_frame);
            descFrame = (ScrollView)dialogRoot.findViewById(R.id.update_content_frame);
            resLoadingFrame = (LinearLayout)dialogRoot.findViewById(R.id.update_res_loading_frame);
            if(dialog != null && dialog.isShowing()){
                dialog.dismiss();
                dialog = null;
            }
            dialog = ViewInject.getDialogView(activity);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            dialog.getWindow().setContentView(dialogRoot);
            progressFrame.setVisibility(View.GONE);
            title.setText("发现新版本");
            content.setText(TimeUtils.timeLong2String(updateTime.getTime(), "yyyy年MM月dd日更新") + "\n" + desc);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    dialog = null;
                }
            });
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    downLoadApk(mContext, SERVER_URL + url);
                    dialog.dismiss();
                    dialog = null;
                }
            });
        }
    }

    /**
     * 从服务器中下载APK
     */
    public static void downLoadApk(Context context, String url) {
        DownloadManager mManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("防范姐说防范更新中...");
//        request.setDescription("版本");
//        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setMimeType("application/vnd.android.package-archive");
        request.setVisibleInDownloadsUi(true);
        request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "PreventionSis.apk");
        long downloadId = mManager.enqueue(request);
        Toast.makeText(context, "开始下载任务", Toast.LENGTH_SHORT).show();
        LogUtil.d("start download id = " + downloadId);
//        Intent intent = new Intent(context, DownloadService.class);
//        intent.putExtra("downloadId", downloadId);
//        context.startService(intent);
        PreventionSis.getInstance().registerDownloadReceiver(downloadId);
//        UpdateDownloadReceiver receiver = new UpdateDownloadReceiver(downloadId);
//        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
//        filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
//        mContext.registerReceiver(receiver, filter);
    }

    public void installApk(Context context, File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 弹出资源更新提示对话框
     */
    private void showResUpdateDialog(String desc, final String url, Date updateTime, boolean retrieveUpdating) {
        Activity activity = ActivityStack.getInstance().topActivity();
        if(activity == null) return;
        View dialogRoot = LayoutInflater.from(mContext).inflate(R.layout.update_dialog, null, false);
        title = (TextView) dialogRoot.findViewById(R.id.update_title);
        ok = (Button) dialogRoot.findViewById(R.id.update_ok);
        cancel = (Button) dialogRoot.findViewById(R.id.update_cancel);
        content = (TextView) dialogRoot.findViewById(R.id.update_content);
        progressFrame = (RelativeLayout) dialogRoot.findViewById(R.id.update_res_progress_frame);
        descFrame = (ScrollView) dialogRoot.findViewById(R.id.update_content_frame);
        resLoadingFrame = (LinearLayout) dialogRoot.findViewById(R.id.update_res_loading_frame);
        stateTxt = (TextView) dialogRoot.findViewById(R.id.update_res_progress_state);
        progressBar = (ProgressBar) dialogRoot.findViewById(R.id.update_res_progressbar);
        progressTxt = (TextView) dialogRoot.findViewById(R.id.update_res_progress_txt);
        if(retrieveUpdating){
            progressFrame.setVisibility(View.VISIBLE);
            descFrame.setVisibility(View.GONE);
            resLoadingFrame.setVisibility(View.GONE);
            dialog.setCancelable(false);
            ok.setSelected(true);
            ok.setClickable(false);
            ok.setText("下载中");
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mHttpClient.isDownloading(url)) {
                        mHttpClient.stopDownload(url);
                    }
                    isUpdatingRes = false;
                    dialog.dismiss();
                    dialog = null;
                }
            });
            title.setText("下载资源包");
            stateTxt.setText("下载进度:");
            String savePath = mContext.getCacheDir().getAbsolutePath() + File.separator + CACHE_RESFILE;
            mHttpClient.rebindDownloadingCallback(getDownloadCallback(savePath));
        } else {
            progressFrame.setVisibility(View.VISIBLE);
            descFrame.setVisibility(View.VISIBLE);
            progressFrame.setVisibility(View.GONE);
            title.setText("发现新资源版本");
            content.setText(TimeUtils.timeLong2String(updateTime.getTime(), "yyyy年MM月dd日更新") + "\n" + desc);
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    dialog = null;
                }
            });
            ok.setOnClickListener(clickToStartDownload(SERVER_URL + url));
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        dialog = ViewInject.getDialogView(activity);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(dialogRoot);
    }

    View.OnClickListener clickToStartDownload(final String url){
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUpdatingRes = true;
                dialog.setCancelable(false);
                ok.setSelected(true);
                ok.setClickable(false);
                ok.setText("下载中");
                progressFrame.setVisibility(View.VISIBLE);
                descFrame.setVisibility(View.GONE);
                downloadRes(url);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mHttpClient.isDownloading(url)) {
                            mHttpClient.stopDownload(url);
                        }
                        isUpdatingRes = false;
                        dialog.dismiss();
                        dialog = null;
                    }
                });
            }
        };
    }

    private static final int DELAYED_CHECK_UPDATE = 97;
    private static final int MSG_INIT_RES_SUCCESS = 98;
    private static final int MSG_INIT_RES_FAIL = 99;
    private static final int MSG_LOAD_RES_SUCCESS = 100;
    private static final int MSG_LOAD_RES_FAIL = 101;
    private static final int MSG_FINISH = 102;

    private Handler mUIHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DELAYED_CHECK_UPDATE:
                    checkVersion();
                    break;
                case MSG_INIT_RES_FAIL:
                    sendEmptyMessageDelayed(MSG_FINISH, 1000);
                    Toast.makeText(mContext, "资源初始化错误，请重新安装应用", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_INIT_RES_SUCCESS:
                    loadRes();
                    break;
                case MSG_LOAD_RES_SUCCESS:
                    dialog.dismiss();
                    dialog = null;
                    break;
                case MSG_LOAD_RES_FAIL:
                    sendEmptyMessageDelayed(MSG_FINISH, 1000);
                    Toast.makeText(mContext, "资源加载错误，请重新安装应用", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_FINISH:
                    ActivityStack.getInstance().AppExit();
                    break;
            }
        }
    };

    private HttpCallBack getDownloadCallback(final String downloadPath){
        return new HttpCallBack() {
            @Override
            public void onPreStart() {
                super.onPreStart();
            }

            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
                int percent = (int) (current * 100 / count);
                progressBar.setMax(100);
                progressBar.setProgress(percent);
                progressTxt.setText(percent + "%");
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                isUpdatingRes = false;
                stateTxt.setText("下载失败");
                ok.setSelected(false);
                ok.setClickable(true);
                ok.setText("重新下载");
                File saveFile = new File(downloadPath);
                if (saveFile.exists()) {
                    saveFile.delete();
                }
            }

            @Override
            public void onSuccess(File f) {
                super.onSuccess(f);
                isUpdatingRes = false;
                resLoadingFrame.setVisibility(View.VISIBLE);
                progressFrame.setVisibility(View.GONE);
                ok.setSelected(true);
                ok.setClickable(false);
                cancel.setSelected(true);
                cancel.setClickable(false);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            ImageResManager imageResManager = ImageResManager.getInstance();
                            imageResManager.initDownloadRes(downloadPath);
                            mUIHandler.sendEmptyMessage(MSG_INIT_RES_SUCCESS);
                        } catch (Exception e) {
                            LogUtil.e(e);
                            mUIHandler.sendEmptyMessage(MSG_INIT_RES_FAIL);
                        }
                    }
                };
                thread.start();
            }
        };
    }

    private void downloadRes(final String url){
        title.setText("下载资源包");
        stateTxt.setText("下载进度:");
        final String savePath = mContext.getCacheDir().getAbsolutePath() + File.separator + CACHE_RESFILE;
        File saveFile = new File(savePath);
        if(saveFile.exists()){
            saveFile.delete();
        }
        mHttpClient.download(url, new File(savePath), getDownloadCallback(savePath));
    }

    private void loadRes(){
        final ImageResManager imageResManager = ImageResManager.getInstance();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    imageResManager.loadRes();
                    mUIHandler.sendEmptyMessageDelayed(MSG_LOAD_RES_SUCCESS, 1000);
                } catch (IOException e) {
                    LogUtil.e(e);
                    mUIHandler.sendEmptyMessage(MSG_LOAD_RES_FAIL);
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
